package com.taotao.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.taotao.pojo.TbUser;
import com.taotao.service.UserService;

public class ShiroDBRealm extends AuthorizingRealm {

	public static final String SESSION_USER_KEY = "im";

	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		// 把token转换成User对象
		TbUser userLogin = tokenToUser((UsernamePasswordToken) authcToken);
		// 验证用户是否可以登录
		TbUser ui = userService.login(userLogin);
		if (ui == null) {
			throw new UnknownAccountException(); // 异常处理，找不到数据
		}
		// 设置session
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute(SESSION_USER_KEY, ui);
		// 设置session有效时间5分钟
		session.setTimeout(300000);
		// 当前 Realm 的 name
		String realmName = this.getName();
		// 登陆的主要信息: 可以是一个实体类的对象, 但该实体类的对象一定是根据 token 的 username 查询得到的.
		Object principal = authcToken.getPrincipal();
		return new SimpleAuthenticationInfo(principal, ui.getPassword(), ByteSource.Util.bytes(ui.getCredentialsSalt()),
				realmName);
	}

	private TbUser tokenToUser(UsernamePasswordToken authcToken) {
		TbUser user = new TbUser();
		user.setUsername(authcToken.getUsername());
		user.setPassword(String.valueOf(authcToken.getPassword()));
		return user;
	}
}
